package com.sdgakj.rest;

import com.alibaba.fastjson.JSONObject;
import com.sdgakj.entity.User;
import com.sdgakj.enums.EnumUserType;
import com.sdgakj.service.login.UserLoginService;
import com.sdgakj.service.user.UserService;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import org.springside.modules.web.MediaTypes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * user登录的Restful API的controller
 *
 * @author lihegang
 */
@RestController
@RequestMapping(value = "/api/v1/user")
public class UserLoginRestController {
    private static Logger logger = LoggerFactory.getLogger(UserLoginRestController.class);

    @Autowired
    private UserLoginService userLoginService;

    @Autowired
    private UserService userService;

    /*
    * @Title: login
    * @Description: 用户登录
    * @param mobile
    * @param pwd
    * @return String @throws
    */
    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(@RequestParam(value = "username") String username,
                        @RequestParam(value = "userpassword") String userpassword,
                        @RequestParam(value = "headurl") String headurl) {
        // 登录
        String jsonResult = userLoginService.login(username, userpassword);
        return jsonResult;
    }

    /**
     * 短信验证码登陆
     *
     * @param mobile
     * @param code
     * @param cname
     * @param invitecode
     * @param iscoming
     * @return
     */
    @RequestMapping(value = "/newLogin", method = RequestMethod.POST)
    public JSONObject loginByMobileWithCode(
            @RequestParam(value = "mobile", defaultValue = "") String mobile,
            @RequestParam(value = "code", defaultValue = "") String code,
            @RequestParam(value = "cname", defaultValue = "-1") String cname,
            @RequestParam(value = "invitecode", defaultValue = "") String invitecode,
            @RequestParam(value = "udid", defaultValue = "0") String deviceno,
            @RequestParam(value = "iscoming", required = false, defaultValue = "0") String iscoming
    ) {

        JSONObject result = new JSONObject();
        if (StringUtils.isBlank(mobile) || StringUtils.isBlank(code)) {
            result.put("resCode", "0");
            result.put("resMSg", "参数错误!");
            return result;
        }
        result = userLoginService.loginByMobileWithCode(mobile, code, cname, invitecode, iscoming, deviceno);
        return result;
    }


    /**
     * 用户注册
     *
     * @param mobile
     *         电话
     * @param pwd
     *         密码
     * @param code
     *         验证码
     * @return
     */
    @RequestMapping(value = "/register", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String register(@RequestParam(value = "mobile", defaultValue = "0") String mobile,
                           @RequestParam(value = "pwd", defaultValue = "0") String pwd,
                           @RequestParam(value = "code", defaultValue = "0") String code) {
        logger.info("mobile : " + mobile);
        // 验证短信校验码
//		if(deviceno.equals("0")){
//			SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//			deviceno=sdf.format(new Date());
//		}
        String jsonResult = userLoginService.register(mobile, pwd, code);
        return jsonResult;
    }

    /**
     * 这里是重置密码
     *
     * @param mobile
     *         电话
     * @param pwd
     *         密码
     * @param code
     *         验证码
     * @return
     */
    @RequestMapping(value = "/recoverPwd", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String recoverPwd(@RequestParam(value = "mobile", defaultValue = "0") String mobile,
                             @RequestParam(value = "pwd", defaultValue = "0") String pwd,
                             @RequestParam(value = "code", defaultValue = "0") String code) {
        logger.info("mobile : " + mobile);
        // 验证短信校验码
        String jsonResult = userLoginService.recoverPwd(mobile, pwd, code);

        return jsonResult;
    }

    /**
     * 修改密码
     *
     * @param mobile
     *         电话
     * @param pwd
     *         密码
     * @param newPwd
     *         新密码
     * @return
     */
    @RequestMapping(value = "/changePwd", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String changePwd(@RequestParam(value = "mobile", defaultValue = "0") String mobile,
                            @RequestParam(value = "pwd", defaultValue = "0") String pwd,
                            @RequestParam(value = "newPwd", defaultValue = "0") String newPwd) {
        logger.info("mobile : " + mobile);
        // 验证旧密码
        String jsonResult = userLoginService.changePwd(mobile, pwd, newPwd);

        return jsonResult;
    }

    /**
     * 给手机发送验证码
     *
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/sendMsg", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public String sendMsg(@RequestParam(value = "mobile", defaultValue = "0") String mobile) {
        logger.info("mobile : " + mobile);
        String jsonResult = "";
        JSONObject json = new JSONObject();
        logger.info("send message start....");
        try {
            if (!"0".equals(mobile)) {
                jsonResult = userLoginService.sendSmsCode(mobile);
            }
            logger.info("send message success...");
        } catch (Exception e) {
            json.put("resCode", "0");
            json.put("resMsg", e.getMessage());
            jsonResult = json.toJSONString();
            logger.info("send message failure" + e.getMessage());
        }
        return jsonResult;
    }

    /**
     * 注册时给手机发送验证码
     *
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/sendregistmsg", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public String sendRegistMsg(@RequestParam(value = "mobile", defaultValue = "0") String mobile) {
        logger.info("send message start...." + mobile);
        String jsonResult = "";
        JSONObject json = new JSONObject();
        try {
            User user = userService.getUserByTell(mobile, EnumUserType.CUSTOMOR.getCode());
            if (null != user) {
                json.put("resCode", "0");
                json.put("resMsg", "手机号已存在");
                return json.toJSONString();

            }
            if (!"0".equals(mobile)) {
                jsonResult = userLoginService.sendSmsCode(mobile);
            }
            logger.info("send message success...");
        } catch (Exception e) {
            json.put("resCode", "0");
            json.put("resMsg", e.getMessage());
            jsonResult = json.toJSONString();
            logger.info("send message failure" + e.getMessage());
        }
        return jsonResult;
    }

    /**
     * 微信端发送验证码
     *
     * @param mobile
     * @return
     */
    @RequestMapping(value = "/sendwxmsg", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public void sendWXMsg(@RequestParam(value = "mobile", defaultValue = "0") String mobile, HttpServletRequest request, HttpServletResponse response) {
        logger.info("send message start...." + mobile);
        String jsonResult = "";
        Map<String, String> hMap = new HashMap<String, String>();
        try {
            PrintWriter out = response.getWriter();
            String callbackName = request.getParameter("jsoncallback");
            User user = userService.getUserByTell(mobile, EnumUserType.CUSTOMOR.getCode());
            if (null != user) {
                hMap.put("resCode", "0");
                hMap.put("resMsg", "手机号已存在");
                out.write(callbackName + "(" + JSONObject.toJSONString(hMap).toString() + ")");
                return;
            }
            if (!"0".equals(mobile)) {
                jsonResult = userLoginService.sendSmsCode(mobile);
            }
            hMap.put("resCode", "1");
            hMap.put("resMsg", "发送成功");
            out.write(callbackName + "(" + JSONObject.toJSONString(hMap).toString() + ")");
            out.flush();
            out.close();
            logger.info("send message success...");
        } catch (Exception e) {
            hMap.put("resCode", "0");
            hMap.put("resMsg", e.getMessage());
            logger.info("send message failure" + e.getMessage());
        }
    }

    /**
     * 重置管理员密码
     *
     * @param mobile
     *         电话
     * @param pwd
     *         密码
     * @param code
     *         验证码
     * @return
     */
    @RequestMapping(value = "/findadminpwd", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String findadminpwd(@RequestParam(value = "mobile", defaultValue = "0") String mobile,
                               @RequestParam(value = "plainPassword", defaultValue = "0") String pwd,
                               @RequestParam(value = "code", defaultValue = "0") String code, RedirectAttributes redirectAttributes) {
        logger.info("mobile : " + mobile);
        // 验证短信校验码
        userService.recoverAdminPwd(mobile, pwd, code);
        redirectAttributes.addFlashAttribute("message", "重置管理员密码成功，请重新登录！");
        return "redirect:/login";
    }

    /**
     * Ajax请求校验验证码是否正确
     */
    @RequestMapping(value = "/checkcode", method = RequestMethod.GET, produces = MediaTypes.JSON_UTF_8)
    public String checkValidateCode(@RequestParam("mobile") String mobile, @RequestParam(value = "code", defaultValue = "") String valicode) {
        Boolean result = userLoginService.checkValidateCode(mobile, valicode); //获取验证码是否正确
        if (result) {
            return "true";
        } else {
            return "false";
        }
    }

    /**
     * 无账号注册登录
     *
     * @param mobile
     *         账号
     * @param code
     *         验证码
     * @return
     */
    @RequestMapping(value = "/loginNoAccount", method = RequestMethod.POST, produces = MediaTypes.JSON_UTF_8)
    public String loginByNoAccount(@RequestParam(value = "mobile", defaultValue = "0") String mobile,
                                   @RequestParam(value = "code", defaultValue = "0") String code) {
        logger.info("mobile : " + mobile);
        // 验证短信校验码
        String jsonResult = userLoginService.loginByNoAccount(mobile, code);
        return jsonResult;
    }

    @RequestMapping(value = "/checkMobile", method = RequestMethod.GET)
    @ResponseBody
    public JSONObject checkUserMobile(
            @RequestParam(value = "mobile", defaultValue = "") String mobile
    ) {
        JSONObject result = new JSONObject();

        if (StringUtils.isBlank(mobile)) {
            result.put("resCode", "0");
            result.put("resMsg", "手机号码不可为空!");
            return result;
        }
        User user = userService.getUserByLoginName(mobile, EnumUserType.CUSTOMOR.getCode());
        return result;
    }

}
